package com.example.demo.search.poisearch;

import java.util.List;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.demo.R;
import com.example.demo.util.Utils;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * POI信息检索
 */
public class PoiCitySearchActivity extends AppCompatActivity
        implements OnGetPoiSearchResultListener,
        BaiduMap.OnMapClickListener {

    // 地图View实例
    private MapView mMapView = null;

    private BaiduMap mBaiduMap = null;

    private EditText mEditTextCity = null;

    private EditText mEditTextPoi = null;

    private PoiSearch mPoiSearch = null;

    private RecyclerView mRecyclerView = null;

    private TextView mPoiTitle = null;

    private TextView mPoiAddress = null;

    private LinearLayout mLayoutPoiInfo = null;

    private Marker mPoiMarker = null;

    private PoiItemAdapter mPoiItemAdaper = null;

    private BitmapDescriptor mBitmapDescriptor =
            BitmapDescriptorFactory.fromResource(R.drawable.water_drop);

    // 分页
    private int mLoadIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_city_search_main);
        Log.d("which","PoiCitySearchActivity");
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mMapView) {
            mMapView.onResume();
        }
    }

    @SuppressWarnings("checkstyle:WhitespaceAround")
    @Override
    protected void onPause() {
        super.onPause();
        if (null != mMapView) {
            mMapView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPoiSearch != null) {
            mPoiSearch.destroy();
        }

        if (null != mMapView) {
            mMapView.onDestroy();
        }

        if (null != mBitmapDescriptor) {
            mBitmapDescriptor.recycle();
        }
    }

    private void init() {
        initView();
        initMap();

        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
    }

    private void initMap() {
        if (null == mMapView) {
            return;
        }

        mBaiduMap = mMapView.getMap();
        if (null == mBaiduMap) {
            return;
        }

        // 解决圆角屏幕手机，地图logo被遮挡的问题
        mBaiduMap.setViewPadding(30, 0, 30, 0);
        mMapView.showZoomControls(false);

        // 设置初始中心点为北京
        LatLng center = new LatLng(39.963175, 116.400244);
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(center, 12);
        mBaiduMap.setMapStatus(mapStatusUpdate);
        mBaiduMap.setOnMapClickListener(this);
    }

    private void initView() {
        mMapView = findViewById(R.id.mapview);
        mEditTextCity = findViewById(R.id.city);
        mEditTextPoi = findViewById(R.id.poi);

        if (null == mEditTextCity || null == mEditTextPoi) {
            return;
        }

        mEditTextPoi.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                return false;
            }
        });

        mEditTextPoi.addTextChangedListener(new MyTextWatcher());

        mRecyclerView = findViewById(R.id.poiList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        if (null == mRecyclerView) {
            return;
        }
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mPoiItemAdaper = new PoiItemAdapter();
        mPoiItemAdaper.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiInfo poiInfo = mPoiItemAdaper.getItemPoiInfo(position);
                locatePoi(poiInfo);
            }
        });

        mRecyclerView.setAdapter(mPoiItemAdaper);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Utils.hideKeyBoard(PoiCitySearchActivity.this);
            }
        });

        mLayoutPoiInfo = findViewById(R.id.poiInfo);
        if (null == mLayoutPoiInfo) {
            return;
        }

        mPoiTitle = mLayoutPoiInfo.findViewById(R.id.poiTitle);
        mPoiAddress = mLayoutPoiInfo.findViewById(R.id.poiAddress);
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        Log.d("poiInfo","-----------------------------------");
        Log.d("poiInfo","获得poi结果 TotalPoiNum= "+poiResult.getTotalPoiNum()+" 总页数"+poiResult.getTotalPageNum());
        if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            mLoadIndex = 0;
            Toast.makeText(PoiCitySearchActivity.this, "未找到结果", Toast.LENGTH_LONG).show();
            return;
        }

        List<PoiInfo> poiInfos = poiResult.getAllPoi();
        if (null == poiInfos) {
            return;
        }

        // 隐藏之前的
        hidePoiInfoLayout();

        mRecyclerView.setVisibility(View.VISIBLE);

        if (null == mPoiItemAdaper) {
            mPoiItemAdaper = new PoiItemAdapter(poiInfos);
        } else {
            mPoiItemAdaper.updateData(poiInfos);
        }
    }

    /**
     * @param poiDetailResult
     * @deprecated
     */
    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        Utils.hideKeyBoard(this);
    }

    @Override
    public void onMapPoiClick(MapPoi mapPoi) {

    }

    class MyTextWatcher implements TextWatcher {

        /**
         * @param s
         * @param start
         * @param count
         * @param after
         */
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        /**
         * @param s
         * @param start
         * @param before
         * @param count
         */
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() <= 0 && View.VISIBLE == mRecyclerView.getVisibility()) {
                mRecyclerView.setVisibility(View.INVISIBLE);
            }
        }

        /**
         * @param s
         */
        @Override
        public void afterTextChanged(Editable s) {
            // 获取检索城市
            String cityStr = mEditTextCity.getText().toString();
            // 获取检索关键字
            String keyWordStr = mEditTextPoi.getText().toString();
            if (TextUtils.isEmpty(cityStr) || TextUtils.isEmpty(keyWordStr)) {
                return;
            }

            if (View.VISIBLE == mRecyclerView.getVisibility()) {
                mRecyclerView.setVisibility(View.INVISIBLE);
            }
            // 发起请求
            mPoiSearch.searchInCity((new PoiCitySearchOption())
                    .city(cityStr)
                    .keyword(keyWordStr)
                    .pageCapacity(20)
                    .pageNum(mLoadIndex) // 分页编号 仅能获取第mLoadIndex页的数据
                    .cityLimit(true)
                    .scope(1));//---------------------------------------------------------------------------
        }
    }

    private void locatePoi(PoiInfo poiInfo) {
        if (null == poiInfo) {
            return;
        }

        if (null == mRecyclerView || null == mMapView) {
            return;
        }

        mRecyclerView.setVisibility(View.INVISIBLE);

        LatLng latLng = poiInfo.location;

        // 将地图平移到 latLng 位置
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(mapStatusUpdate);

        // 隐藏输入法
        Utils.hideKeyBoard(this);

        // 显示当前的
        showPoiMarker(latLng);
        showPoiInfoLayout(poiInfo);
    }

    /**
     * 显示定位点
     *
     * @param latLng
     */
    private void showPoiMarker(LatLng latLng) {
        if (null == latLng) {
            return;
        }

        if (null == mPoiMarker) {
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(latLng)
                    .icon(mBitmapDescriptor)
                    .scaleX(1.5f)
                    .scaleY(1.5f);
            mPoiMarker = (Marker) mBaiduMap.addOverlay(markerOptions);
        } else {
            mPoiMarker.setPosition(latLng);
        }
    }

    /**
     * 显示底部poi详情
     *
     * @param poiInfo
     */
    private void showPoiInfoLayout(PoiInfo poiInfo) {

        if (null == mLayoutPoiInfo || null == poiInfo) {
            return;
        }

        if (null == mPoiTitle) {
            return;
        }

        if (null == mPoiAddress) {
            return;
        }

        mLayoutPoiInfo.setVisibility(View.VISIBLE);

        mPoiTitle.setText(poiInfo.getName());

        String address = poiInfo.getAddress();
        if (TextUtils.isEmpty(address)) {
            mPoiAddress.setVisibility(View.GONE);
        } else {
            mPoiAddress.setText(poiInfo.getAddress());
            mPoiAddress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏poi详情
     */
    private void hidePoiInfoLayout() {
        if (null == mLayoutPoiInfo) {
            return;
        }

        mLayoutPoiInfo.setVisibility(View.GONE);
    }
}
